import glob
import os

from fpdf import FPDF


def get_images(subfolder):
    """获取图片数组

    Args:
        subfolder (_type_): _description_

    Returns:
        _type_: _description_
    """
    images = []
    for root, dirs, files in os.walk(subfolder):
        for file in files:
            if file.endswith('.jpg'):
                images.append(os.path.join(root, file))
    return images

def images_to_pdf(folder_path):
    """批量图片转pdf

    Args:
        folder_path (_type_): _description_
    """
    subfolders = [f.path for f in os.scandir(folder_path) if f.is_dir()]

    for subfolder in subfolders:
        # 跳过已存在的
        if os.path.exists(subfolder):
            print(f"PDF:{os.path.basename(subfolder) + '.pdf'} 已存在")
            continue
    
        pdf = FPDF()
        images = get_images(subfolder)

        if len(images) > 0:
            for image in images:
                pdf.add_page()
                pdf.image(image, 0, 0, 210, 297)  # 调整页面大小适应 A4

            pdf.output(os.path.join(
                folder_path, os.path.basename(subfolder) + '.pdf'))
            
            # # 删除图片
            # for jpg_file in images:
            #     # 先删除图片
            #     try:
            #         os.remove(jpg_file)
            #     except Exception as e:
            #         print(f"删除图片 {jpg_file} 时出错: {e}")
            
            # # 删除子文件夹
            # try:
            #     os.rmdir(subfolder)
            # except OSError as e:
            #     if e.errno != 66:  # 66 表示目录不为空的错误码
            #         raise e
            
            print(f"PDF:{os.path.basename(subfolder) + '.pdf'}生成完成")


folder_path = 'G:\\H图片\\日本漫画'
images_to_pdf(folder_path)
